/*
 * @Author: AskMeWhy
 * @Date: 2020-12-27 11:58:47
 * @Last Modified by: AskMeWhy
 * @Last Modified time: 2020-12-30 10:31:58
 */
const app = getApp();
const { AskComponent } = app._require("common/index");
AskComponent({
    properties: {
        items: {
            type: Array,
            value: [],
            observer: "buildItem",
        },
        actives: {
            type: Array,
            value: []
        },
        itemKey: {
            type: String,
            value: "label",
        },
        itemValue: {
            type: String,
            value: "value",
        },
        itemChildren: {
            type: String,
            value: "children",
        },
    },
    data: {
        treeData: {},
        nodeData: [],
    },
    methods: {
        buildItem() {
            let nodeData = this.buildNodeData(this.data.items, 0);
            this.setData({
                nodeData,
            });
        },
        buildNodeData(list, index) {
            let res = [];
            for (let i = 0; i < list.length; i++) {
                const cur = list[i];
                let _key = index + "-" + i;
                const _cur = {
                    label: cur.label || "",
                    value: cur.value || index + "-" + i,
                    children: [],
                    index: _key.split("-").slice(1),
                    checked: false,
                };
                if (cur.children && cur.children.length > 0) {
                    _cur.children = this.buildNodeData(cur.children, index + "-" + i);
                }
                _cur.checked = this.data.actives.includes(_cur.value);
                this.data.treeData[_cur.value] = _cur;
                res.push(_cur);
            }
            return res;
        },
        setChecked(id, checked) {
            let _index = this.data.treeData[id].index;
            let _key = "";
            _index.forEach((cur, index) => {
                _key += index === 0 ? "[" + cur + "]" : "children[" + cur + "]";
            });
            this.setData({
                ["nodeData" + _key + ".checked"]: checked,
            });
        },
        handleChange(e) {
            this.$emit("change", e.detail);
        },
    },
});
